import { Component } from 'react';

import { SelectField, CheckboxField, TextareaField,TextField,Group,DatetimeField,Datetime,Toast,Button,SwitchField,Boxs } from 'saltui';
const { HBox,Box,VBox } = Boxs;
import './form.less';
import AngleRight from 'salt-icon/lib/AngleRight';
import CommentList from 'components/comment_list';
import Upload from 'components/upload';
import Form from 'components/form/form';
import Positioning from 'components/positioning';
//import 'babel-polyfill';
import Poppage from 'components/poppage';
import SelectMember from 'components/selectMember';
let FlowCommon ;
export default class PageHome extends Component {

  constructor(props) {
    super(props);
    var form = props.form;
    var data = props.data;
    var status = props.status;
    var context = document.getElementById("context").value;

    let module = props.module;
    FlowCommon = require('pages/flow_common/'+module);
    this.state = {
      module:module,
      status: status,
      fieldControll:props.fieldControll,
      urlPrev: context + '/dingisv/api/common/viewImage?fid=',
      calc:[],
      itemParam:{
        readOnly:false,
        required:false,
        title:'',
        value:'',
        itemType:'',
        id:'',
        key:''
      },
      loaded:false,
      commentList:[]
    };

  }


  //流程控制表单字段显示
  fieldControllFormat(field,fieldControll){
    // let isHidden = null;
    // let required = null;
    // let readOnly = null;
    let status = null;
    if(fieldControll){
      let hiddenFields = fieldControll.hiddenFields;
      let mustFields = fieldControll.mustFields;
      let showFields = fieldControll.showFields;
      let editFields = fieldControll.editFields;
      let assignFieldIds = fieldControll.assignFieldIds;//赋值
      
      if(assignFieldIds){ //是否赋值
        assignFieldIds = ","+assignFieldIds+",";
        if(assignFieldIds.indexOf(","+field+",")>=0){//是否包含字段
          status = "assign&";
        }
      }

      if(hiddenFields){ //是否隐藏
        hiddenFields = ","+hiddenFields+",";
        if(hiddenFields.indexOf(","+field+",")>=0){//是否包含字段
          status += "hidden";
          return status;
        }
      }

      if(showFields){ //是否只读
        showFields = ","+showFields+",";
        if(showFields.indexOf(","+field+",")>=0){//是否包含字段
          status += "show";
          return status;
        }
      }

      if(editFields){ //是否可编辑
        editFields = ","+editFields+",";
        if(editFields.indexOf(","+field+",")>=0){//是否包含字段
          status += "edit";
          if(mustFields){ //是否必须
            mustFields = ","+mustFields+",";
            if(mustFields.indexOf(","+field+",")>=0){//是否包含字段
              status += "&must";
              return status;
            }
          }
          return status;
        }
      }

      if(mustFields){ //是否必须
        mustFields = ","+mustFields+",";
        if(mustFields.indexOf(","+field+",")>=0){//是否包含字段
          status = "must";
          return status;
        }
      }

      return status;

    } 
  }

  //加载组件
  loadComponet(formItem){
    let t = this;
    var form;
    if(formItem){//二次修改传的formitem属性
      form = formItem;
    }else{
      form = this.props.form; //表单元素
    }
    var status = this.props.status; //判断是否能选择,0新增，1修改,2查看
    var data = this.props.data; //数据
    var dataType = this.props.dataType;//数据类型，main:主表，sub：子表，
    if(!dataType){
      dataType = "main";
    }
    if(dataType == "sub"){
    }
    var tableName = data.mainTblName;
    var itemParam = {};  //元素参数
    itemParam.tableName=tableName;
    itemParam.uniqueName=form.uniqueName;
    var commentList = this.props.commentList;
    if(!commentList){
      commentList = [];
    }

    var id = form.id;
    itemParam.id=id;
    var title = form.itemTitle; //标题
    itemParam.title=title;
    var key = form.itemCode; //表字段;
    itemParam.key=key;
    var itemType = form.itemType; //类型
    itemParam.itemType=itemType;
    var required = form.valid == "true";//必填
    itemParam.required=required;
    var placeholder = form.placeholder;//提示语
    itemParam.placeholder = placeholder;
    itemParam.defaultValue=form.value;
    var regexStr = form.regexStr;//扩展字段，包括长度，类型等
    var maxLength = 0;//最大长度，0为不限制
    if(regexStr){
      regexStr = JSON.parse(regexStr);
      if(Array.isArray(regexStr)){//集合

      }else{
        var ownAttr = regexStr.ownAttr;//
        ownAttr = JSON.parse(ownAttr);
        if(ownAttr.maxLength){//
          maxLength = parseInt(ownAttr.maxLength);
        }
      }
    }
    itemParam.maxLength=maxLength;
    itemParam.cannotEdit=true;//移动端可以编辑

    itemParam.isHidden = false;//默认不隐藏
    
    var mainTblData = data.mainTblData;//主表数据
    var subTbl = data.subTbl;//子表
    var readOnly = false;
    var assign = false;//是否赋值
    var value = '';

    if(key != ""){
      //判断字段属性
      let fieldControllJson = this.props.fieldControll;
      let hasAssignFieldIds = "";
      if(fieldControllJson){
        hasAssignFieldIds = fieldControllJson.hasAssignFieldIds==null?"":fieldControllJson.hasAssignFieldIds;//判断新老流程，老的为空，新的为0/1
        let fieldControll = this.fieldControllFormat(tableName+"_"+key,fieldControllJson);
        if(fieldControll){
          if(fieldControll.indexOf('assign')>=0){//赋值
            assign = true;
          }
          if(fieldControll.indexOf('hidden')>=0){//隐藏
            itemParam.isHidden = true;
          }else{
            if(fieldControll.indexOf('show')>=0){//只读
              readOnly = true;
              required = false;
            }else{
              if(fieldControll.indexOf('edit')>=0){//编辑
                readOnly = false;
              }
              if(fieldControll.indexOf('must')>=0){//必填
                required = true;
              }
            } 
          } 
        }
          
      }
      itemParam.assign = assign;
      itemParam.readOnly = readOnly;
      itemParam.required = required;
      //处理数据
      var tableData = {};
      if (status == '0') {//新增 
        tableData.key = key;
        if(hasAssignFieldIds == "" || (hasAssignFieldIds != "" && assign==true)){//新流程且赋值了属性
          value = form.value;
        }else{
          value = "";
        }
        tableData.value = value;
        tableData.required = required;
        tableData.label = title;
        mainTblData.push(tableData);
      } else if(status == '1') {//编辑
        var dataId = data.dataId;
        if(!dataId){
          if(dataType == "sub"){
            if(this.checkIsHasSub(mainTblData,key)){
              value = this.dealwithData(itemParam,mainTblData);
            }else{
              tableData.key = key;
              if(hasAssignFieldIds == "" || (hasAssignFieldIds != "" && assign==true)){//新流程且赋值了属性
                value = form.value;
              }else{
                value = "";
              }
              tableData.value = value;
              tableData.required = required;
              tableData.label = title;
              mainTblData.push(tableData);
            }
          }else{
            tableData.key = key;
            if(hasAssignFieldIds == "" || (hasAssignFieldIds != "" && assign==true)){//新流程且赋值了属性
              value = form.value;
            }else{
              value = "";
            }
            tableData.value = value;
            tableData.required = required;
            tableData.label = title;
            mainTblData.push(tableData);
          }
        }else{
          value = this.dealwithData(itemParam,mainTblData); //初始化值
        }
      }else{//显示
        readOnly = true;
        required = false;
        itemParam.required = required;
        itemParam.readOnly = readOnly;
        value = this.dealwithData(itemParam,mainTblData); //初始化值
      }
    }


    // if(status == '2'){//只读
    //   readOnly = true;
    //   itemParam.readOnly = readOnly;
    //   required = false;
    //   itemParam.required = required;
    // }else{
    //   tableData.required = required;
    //   tableData.label = title;
    //   mainTblData.push(tableData);
    // }
    if (itemType == 'text') {//单行文本框
      itemParam.inputFormat = form.inputFormat;//文本类型
      itemParam.decimalPlace = form.decimalPlace;//小数位数
      var calculateExpList = data.calculateExpList;//计算公式列表
      var calculateExp = form.calculateExp;//计算公式
      if(calculateExp){
        var fieldArray = this.getFieldArray(calculateExp);
        for(var i=0; i<fieldArray.length; i++){
          var calculateExpValue;
          if(calculateExpList){
            calculateExpValue = calculateExpList[fieldArray[i]];
            if(!calculateExpValue){
              calculateExpValue = [];
            }
          }else{
            calculateExpList = {};
            calculateExpValue = [];
          }
          
          var calculateExpValueItem = {};
          calculateExpValueItem.exp = calculateExp;//计算公式
          calculateExpValueItem.result = form.uniqueName;//公式结果字段
          calculateExpValueItem.key = key;//公式结果字段key
          calculateExpValue.push(calculateExpValueItem);
          calculateExpList[fieldArray[i]] = calculateExpValue;
        }
        data.calculateExpList = calculateExpList;
      }


      // if(item.calcExpressionType.length>0){//计算公式
      //   var calcExpressionType = item.calcExpressionType;
      //   var calcExpression = item.calcExpression;
      //   for(var i=0; i<calcExpressionType.length<0; i++){
      //     if(calcExpressionType[i]!='0'){ //代表字段

      //     }
      //   }
      // }

    } else if(itemType == 'textarea') {//多行

    } else if (itemType == 'radio') { //单选
      var selectItem = form.multiItems;//选项
      var selectOptions = [];
      if(selectItem){
        if(selectItem.length>0){
          selectItem.map(function(item){
            var option = {};
            option.value = item.value;
            option.text = item.name;
            // if(status != '0'){
              if(value == item.value){
                value = {value:value,text:item.name};
              }
            // }
            selectOptions.push(option);
          });
        }
      }
      if(value == ""){
        value = null;
      }
      itemParam.selectOptions = selectOptions;
    } else if (itemType == 'checkbox') { //多选
      if(typeof FlowCommon.messagePushSwitchOption === "function"){
        form = FlowCommon.messagePushSwitchOption(form);
      }
      var selectItem = form.multiItems;//选项
      var selectOptions = [];
      if(selectItem){
        var valueArray = [];
        // if(status != '0'){
          if(value != 0 && value){
            valueArray = value.split(",");
          }
        // }
        if(selectItem.length>0){
          selectItem.map(function(item){
            var option = {};
            option.value = item.value;
            option.text = item.name;
            option.disable = false;
            option.checked = false;
            if(valueArray.length>0){
              for(var i=0;i<valueArray.length;i++){
                if(valueArray[i] == item.value){
                  option.checked = true;
                }
              }
            }
            selectOptions.push(option);
          });
        }
      }
      itemParam.selectOptions = selectOptions;
    } else if (itemType == 'select') { //下拉选择
      var selectItem = form.multiItems;//选项
      var selectOptions = [];
      if(selectItem){
        if(selectItem.length>0){
          selectItem.map(function(item){
            var option = {};
            option.value = item.value;
            option.text = item.name;
            if(status != '0'){ //非新增
              if(value == item.value){
                value = {value:value + "",text:item.name};
              }
            }else{
              var defaultValue=form.defaultValue;
              if(defaultValue == item.value){
                value = {value:value,text:item.name};
              }
            }
            selectOptions.push(option);
          });
        }
      }
      if(value == ""){
        value = null;
      }
      itemParam.selectOptions = selectOptions;
    } else if (itemType == 'datetime') { //时间
      var dateFormat = form.dateFormat;
      if(!dateFormat){
        dateFormat = "YMD";
      }
      itemParam.dateFormat = dateFormat;
      if(value){
        value = value.substring(0,19);
        value = new Date(value.replace(/-/g,"/")).getTime(); 
      }else{
        // if(status == '0'){
        //   value = new Date().getTime();
        // }else{
          value=null;
        // }
      }
    }else if (itemType == 'datetimeStep') { //时间
      var dateFormat = form.dateFormat;
      if(!dateFormat){
        dateFormat = "YMD";
      }
      itemParam.dateFormat = dateFormat;
      itemParam.selectValue = form.selectValue;
      if(value){
        value = new Date(value.replace(/-/g,"/")).getTime(); 
      }else{
        value = new Date().getTime();
      }
    } else if (itemType == 'scale') { //矩阵
    } else if (itemType == 'mulscale') { //矩阵量表
    }else if(itemType == 'comment'){//批示意见
      var commentFieldList = [];
      for(let i=0; i<commentList.length; i++){
        var commentItem = commentList[i];
        if(commentItem.field == tableName+'_'+key){//评论id和code
          commentFieldList.push(commentItem);
        }
      }
      itemParam.topicType = itemType;
      value =  commentFieldList;
    }else if(itemType == 'upload' ||itemType == 'image'){//附件图片
      var uploadFileNumLimit = form.uploadFileNumLimit;//上传个数限制
      var uploadFileLimit = form.uploadFileLimit;//上传类型限制
      if(value){
        value = value.replace(/\|/g,",");
        itemParam.initIds = value;
        value = [];
      }else{
        value = [];
      }
      if(uploadFileNumLimit){
        itemParam.uploadFileNumLimit = uploadFileNumLimit;
      }else{
        itemParam.uploadFileNumLimit = -1;
      }

      if(uploadFileLimit){
        itemParam.uploadFileLimit = uploadFileLimit;
      }else{
        itemParam.uploadFileLimit = "";
      }
    }else if(itemType == 'weboffice'){//在线编辑

    }else if(itemType == 'poppage'){//弹出选择
      
      var popCode = "";
      var chooseWay = "checkbox";
      if(form.poppageMap){
        popCode = form.poppageMap.chooseObj;
        chooseWay = form.poppageMap.chooseWay;
      }
      if(popCode == ''){//如果弹出选择的编码为空
        Toast.show({
          type: 'error',
          content:"弹出选择组件设置异常！"
        });
        return false;
      }
      itemParam.chooseWay = chooseWay;
      itemParam.popCode = popCode;
    }
    else if(itemType == 'popuser'){//弹出选择
      var popCode = "";
      var chooseWay = "checkbox";
      var scopeTable = "";
      if(form.popuserMap){
        popCode = form.popuserMap.chooseObj;
        chooseWay = form.popuserMap.chooseWay;
        scopeTable = form.popuserMap.scopeTable;
      }
      if(popCode == ''){//如果用户选择的编码为空
        Toast.show({
          type: 'error',
          content:"用户选择组件设置异常！"
        });
        return false;
      }
      itemParam.checkType = chooseWay;
      itemParam.code = popCode;
      itemParam.fieldTable = tableName;
      itemParam.fieldData = key;
      itemParam.scopeTable = scopeTable;
      itemParam.isDelete = true;
    }else if(itemType == 'note'){//说明
      itemParam.explain = form.explain;
      itemParam.explainUrl = form.explainUrl;
      itemParam.explainShow = form.explainShow;
    }else if(itemType == 'switch'){//开关
      if(status != '0'){ //非新增
        if(value){
          if(value == '1'){
            value=true;
          }else{
            value=false;
          }
        }else{
          value = false;
        }
      }else{
        var defaultValue=form.defaultValue;
        if(defaultValue){
          if(defaultValue == '1'){
            value=true;
          }else{
            value=false;
          }
        }else{
          value = false;
        }
      }
      
    }else if(itemType == 'positioning'){//地图定位
    }
    
    itemParam.value = value;
   
    //处理特有按钮事件
    if(typeof FlowCommon.dealwithCommonFormParam === "function"){
      itemParam = FlowCommon.dealwithCommonFormParam(itemParam,this);
      itemType = itemParam.itemType;
    }
    this.setState({
      itemParam: itemParam,
      loaded:true
    },function(){
      if(itemType == 'popuser'){
         this.refs['selectMember_'+key].initSelectData();
      }
      if(itemType == 'upload' || itemType == 'image'){
        this.refs["upload"+t.state.itemParam.tableName+"_"+t.state.itemParam.key].initData();
      }
    });
    this.props.onChange(data);
  }

  
//从计算表达式中获取涉及的字段
getFieldArray(exp){
	var fieldArray=[];
	var expProcessStepOne=exp.split('[');
	for(var i=1;i<expProcessStepOne.length;i++){
		var expProcessStepTwo=expProcessStepOne[i].split(']');
		if(expProcessStepTwo.length>0){
			var fieldUniqueName=expProcessStepTwo[0];
			if(fieldUniqueName.length>0){
				fieldArray.push(fieldUniqueName);
			}
		}
	}
	return fieldArray;
}

  componentDidMount() {
    this.loadComponet();

    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : "预定会议室",//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: "预定会议室",
            icon: '',
            actionmenu: {}
        },
      });
    }
  }

  //重新加载组件
  reloadItemParam(itemNew){
    if(itemNew != null && itemNew != undefined && Array.isArray(itemNew)){
      var itemParam = this.state.itemParam;
      for(var i=0; i<itemNew.length; i++){
        var key = itemNew[i].key;
        if(key == 'value' && itemParam.itemType=='positioning'){//当key是value且组件是定位时
          itemParam.value = {name:itemNew[i].value};
        }else{
          itemParam[key] = itemNew[i].value;
        }
      }
      this.setState({
        itemParam:itemParam
      });
    }
  }

  //获取字段的itemParam属性
  getItemParam(){
    var itemParam = this.state.itemParam;
    return itemParam;
  }


  //检查是否有子
  checkIsHasSub(mainTblData,code){
    var result = false;
    for(var i=0;i<mainTblData.length; i++){
      if(mainTblData[i].key == code){
        result = true;
      }
    }
    return result;
  }
   //处理主表数据
   dealwithData(itemParam,mainTblData){
    var itemCode = itemParam.key;
    var itemType = itemParam.itemType;
    var assign = itemParam.assign;
    var defaultValue = itemParam.defaultValue;
    var value = '';
    if(mainTblData.length>0){
      for(var i=0;i<mainTblData.length;i++) { 
        var item = mainTblData[i];
        if(item.key==itemCode){
          mainTblData[i].required = itemParam.required;//是否必填
          mainTblData[i].label = itemParam.title;//标题
          //mainTblData[i].maxLength = itemParam.maxLength;//支持最大长度
          
          // if(item.showValue){
          //   value = item.showValue;
          //   item.showValue = null;
          // }else{
            if(assign == true && defaultValue != ''){//当字段是赋值时且默认值不为空
              value = defaultValue;
            }else{
              if(item.value != null) value = item.value;
            }
            
          //}
          
          if(assign == true && defaultValue != ''){//当字段是赋值时且默认值不为空
            mainTblData[i].value = defaultValue+'';
          }else{
            if(itemType == 'text' || itemType == 'textarea'){
              if(value){
                mainTblData[i].value = value+'';
              }
            }
          }
          break;
        }
      };
      return value;
    }else{
      return value;
    }
  }

  //处理子表数据
  dealwithSubForm(subForm,itemParam,subTbl){
    var subFormList = [];
    subForm = {show:true,form:subForm};
    var itemCode = itemParam.key;
    var value = [];
    if(subTbl.length>0){
      for(var i=0;i<subTbl.length;i++) { 
        var item = subTbl[i];
        if(item.subTblName==itemCode){
          var subTblData = item.subTblData;
          if(subTblData.length>0){
            for(var j=0;j<subTblData.length;j++) { 
              value.push({mainTblData:subTblData[j],mainTblName:itemCode});
              subFormList.push(subForm);
            }
          }else{
            value.push({mainTblData:[],mainTblName:itemCode});
            subFormList.push(subForm);
          }
          break;
        }
      }
    }
    if(subFormList.length>0){
      itemParam.subForm = subFormList;
    }else{
      subFormList.push(subForm);
      itemParam.subForm = subFormList;
      value.push({mainTblData:[],mainTblName:itemCode});
      subTbl.push({subTblData:[],subTblName:itemCode});
    }
    return value;
  }


  //修改data数据
  editData(itemCode,value,data){
      //处理操作返回数据
      if(typeof FlowCommon.dealwithReturnData === "function"){
        FlowCommon.dealwithReturnData(itemCode,value,function(itemCode1,value1){
          itemCode=itemCode1;
          value=value1;
        });
      }
      if(Array.isArray(itemCode) && Array.isArray(value)){//数组时
        for(var i=0; i<itemCode.length; i++){
          var mainTblData = data.mainTblData;
          mainTblData.map(function(item,index){
            if(item.key==itemCode[i]){
              item.value = value[i];
            }
          });
        }
      
      }else{
        var mainTblData = data.mainTblData;
        mainTblData.map(function(item,index){
          if(item.key==itemCode){
            item.value = value;
          }
        });
      }
    
    return data;
  }

  //文本
  handleTextChange(item, newValue) {
    var maxLength = item.maxLength;
    if(maxLength !=0 && newValue.length>maxLength){//当限制了输入长度且输入长度超过了限制时
      return false;
    }
    var inputFormat = item.inputFormat;
    var decimalPlace = parseInt(item.decimalPlace);
    var patrn = /^\d+(\.\d+)?$/;
    if(newValue != ''){
      if(inputFormat == 'float'){
        if(!Number(newValue) && !patrn.test(Number(newValue))){
          Toast.show({
            type: 'error',
            content:item.title+"应为小数"
          });
          return false;
        }else{
          var newValueArray =  newValue.split(".");
          if(newValueArray.length>1){
            if(newValueArray[1].length>decimalPlace){
              Toast.show({
                type: 'error',
                content:"小数位应不大于"+decimalPlace
              });
              return false;
            }
          }
        }
      }else if(item.key == 'interval_date'){
        if(!/^-?[0-9]\d*$/.test(newValue)){
          Toast.show({
            type: 'error',
            content:item.title+"应为非负整数"
          });
          return false;
        }
      }else if(inputFormat == 'int'){
        if(!/^-?[0-9]\d*$/.test(newValue)){
          Toast.show({
            type: 'error',
            content:item.title+"应为整数"
          });
          return false;
        }
      }
    }
    var name = item.key;
    var data = this.props.data;
    data = this.editData(name,newValue,data);
    var itemParam = this.state.itemParam;
    itemParam.value = newValue;
    this.setState({
      itemParam: itemParam
    });
    
    this.props.onChange(data,itemParam);
  }


  //多行文本
  handleTextAreaChange(item, newValue) {
    var maxLength = item.maxLength;
    if(maxLength !=0 && newValue.length>maxLength){//当限制了输入长度且输入长度超过了限制时
      return false;
    }
    var name = item.key;
    var data = this.props.data;
    data = this.editData(name,newValue,data);
    var itemParam = this.state.itemParam;
    itemParam.value = newValue;
    this.setState({
      itemParam: itemParam
    });
    this.props.onChange(data);
  }

  //多选
  checkboxChange(code,value) {
    var data = this.props.data;
    var valueStr = '';
    for(var i=0;i<value.length;i++){
      valueStr += value[i].value+",";
    }
    if(valueStr!=''){
      valueStr = valueStr.substring(0,valueStr.length-1);
    }

    data = this.editData(code,valueStr,data);
    // var itemParam = this.state.itemParam;
    // itemParam.selectOptions = radioData;
    // this.setState({
    //   itemParam: itemParam
    // });
    this.props.onChange(data);
    //console.log(value, index, data);
  }

  //单选
  radioChange(code,value) {
    var data = this.props.data;
    data = this.editData(code,value,data);
    // var itemParam = this.state.itemParam;
    // itemParam.selectOptions = radioData;
    // this.setState({
    //   itemParam: itemParam
    // });
    this.props.onChange(data);
    //console.log(value, index, data);
  }

   //下拉
   selectChange(code,value){
    var data = this.props.data;
    var selectValue = value.value;
    data = this.editData(code,selectValue,data);
    var itemParam = this.state.itemParam;
    itemParam.value = value;
    this.setState({
      itemParam: itemParam
    });
    this.props.onChange(data,itemParam);
  }

  //时间
  handleChangeDate(code,value){
    var data = this.props.data;
    var itemParam = this.state.itemParam;
    var dateFormt = itemParam.dateFormat;

    var dateStr = this.dateFormat(value.value,dateFormt);
    data = this.editData(code,dateStr,data);
    
    itemParam.value = value;
    this.setState({
      itemParam: itemParam
    });
    this.props.onChange(data,itemParam);
  }

  //时间步进
  handleChangeDateStep(code,value){
    var data = this.props.data;
    var itemParam = this.state.itemParam;
    var dateFormt = itemParam.dateFormat;

    var dateStr = this.dateFormat(value.value,dateFormt);
    data = this.editData(code,dateStr,data);
    itemParam.value = value;
    itemParam.selectValue = dateStr;
    this.setState({
      itemParam: itemParam
    });
    this.props.onChange(data);
  }

  showSlot(id) {
    this[id].show();
  }

  //时间转换
  dateFormat(date,formatStr){
    date = new Date(date);
    var year = date.getFullYear();
    var month = this.dealwithDate(date.getMonth()+1);
    var dates = this.dealwithDate(date.getDate());
    if(formatStr =='YMD'){//年月日
      return year+'-'+month+'-'+dates;
    }else if(formatStr =='YMDHM'){//年月日时分
      var hour = this.dealwithDate(date.getHours());
      var min = this.dealwithDate(date.getMinutes());
      return year+'-'+month+'-'+dates+' '+hour+':'+min;
    }else{
      return '';
    }
    
  }

  dealwithDate(date){
    if(date>=10){
      return date;
    }else{
      return '0'+date;
    }
  }


  //附件、图片
  handleChangePic(code,data,isInitIds) {
    var itemParam = this.state.itemParam;
    itemParam.value = data;
    itemParam.initIds = "";
    this.setState({
      itemParam: itemParam
    });
    if(isInitIds != '1'){
      //处理上传附件
      let fileids = '';
      data.map(function(item){
        fileids += item.id+",";
      });
      if(fileids != ''){
        fileids = fileids.substring(0,fileids.length-1);
      }
      var data = this.props.data;
      fileids = fileids.replace(/,/g,"|");
      data = this.editData(code,fileids,data);
      this.props.onChange(data);
    }

  }

  //弹出选择
  popageChange(code,newValue){
    var data = this.props.data;
    data = this.editData(code,newValue,data);
    var itemParam = this.state.itemParam;
    itemParam.value = newValue;
    this.setState({
      itemParam: itemParam
    });
    this.props.onChange(data);
  }

  //用户选择
  popuserChange(code,newValue,oldValue){
    //alert(JSON.stringify(newValue));
    var data = this.props.data;
    if(newValue){
      if(newValue.length==0){
        newValue = "";
      }else{
        newValue = JSON.stringify(newValue);
      }
    }else{
      newValue = "";
    }
    data = this.editData(code,newValue,data);
    // var itemParam = this.state.itemParam;
    // itemParam.value = newValue;
    // this.setState({
    //   itemParam: itemParam
    // });
    this.props.onChange(data);
    // var json = [
    //   {"scopeValue":'113',"scopeType":"user","scopeName":"葛萌"}
    // ];
    
  }

  //开关切换方法
  handleWitchChange(code,newValue){
    var data = this.props.data;
    var itemParam = this.state.itemParam;
    itemParam.value = newValue;

    var realValue = newValue?'1':'0';
    data = this.editData(code,realValue,data);
    
    this.setState({
      itemParam: itemParam
    });
    this.props.onChange(data,itemParam);
  }

  //定位方法
  handlePositionChange(code,newValue){
    var data = this.props.data;
    var itemParam = this.state.itemParam;
    itemParam.value = newValue;

    data = this.editData(code,newValue,data);
    
    this.setState({
      itemParam: itemParam
    });
    this.props.onChange(data);
  }




  //矩阵评分
  changeScale(value) {

    var keyNo = this.props.keyNo;
    var list = this.props.data[keyNo].list;
    this.props.data[keyNo].answer = list[value - 1].id;
    this.props.data[keyNo].itemNo = value;
    this.props.data[keyNo].isAnswer = 1;
    this.props.onChange(this.props.data);
  }

  //矩阵变量
  changeMulScale(no,value){
    var keyNo = this.props.keyNo;
    var list = this.props.data[keyNo].answer[no].list;
    this.props.data[keyNo].answer[no].value = list[value - 1].optionOrder;
    this.props.data[keyNo].answer[no].itemNo = parseInt(list[value - 1].optionOrder)+1;
    this.props.data[keyNo].answer[no].fraction = list[value - 1].optionScore;
    this.props.data[keyNo].answer[no].isAnswer = 1;
    this.setState({
      data:this.props.data[keyNo]
    });
    this.props.onChange(this.props.data);
  }


  //明细删除
  detailDel(i){
    var itemParam = this.state.itemParam;
    var subForm = itemParam.subForm;
    subForm.splice(i,1);
    itemParam.value.splice(i,1);
   // itemParam.subForm = subForm;
    var data = this.props.data;
    var subTblList = data.subTbl;
    for(var i=0; i<subTblList.length; i++){
      if(subTblList[i].subTblName == itemParam.key){
        subTblList[i].subTblData.splice(i,1);
      }
    }
     this.setState({
      itemParam:itemParam,
   });
   this.props.onChange(data);
  }


  //添加明细
  detailAdd(){
    var form = this.props.form; //表单元素
    var data = this.props.data; //表单数据
    var subTbl = data.subTbl;
    var formItem = form.children;
    //var subForm = {show:true,form:formItem};
    var itemParam = this.state.itemParam;
    //itemParam.subForm.push(subForm);

    this.addSubForm(formItem,itemParam,subTbl);
    data.subTbl = subTbl;
    this.setState({
      itemParam:itemParam,
    });
    this.props.onChange(data);
  }

  //新增明细处理数据
  addSubForm(subForm,itemParam,subTbl){
    var subFormList = itemParam.subForm;
    subForm = {show:true,form:subForm};
    var itemCode = itemParam.key;
    var value = itemParam.value;
    subFormList.push(subForm);
    itemParam.subForm = subFormList;
    value.push({mainTblData:[],mainTblName:itemCode});
    return value;
  }

  getDetai(){
    let t =this;
    var subForm = this.state.itemParam.subForm;
    return subForm.map((item, i) => {
      return (
        <div className="dd-drug-list">
          <HBox className="t-BCf dd-bottom-border">
            <Box  className="t-LH44 t-PL16 t-PR2"><i className={item.show?"iconfont icon-arrow-down t-FS18 t-FCc":"iconfont icon-arrow-up t-rotate-90 t-FS18 t-FCc"} ></i></Box>
            <Box flex={1} className="t-LH46 t-FC9" onClick={this.detailShow.bind(this,i,item.show)}>{i+1}</Box>
            <Box data-key={i} onClick={this.detailDel.bind(this,i)} className='t-P16 t-FCddblue'>删除</Box>
          </HBox>
          <div className={item.show ?"":"t-DN"}>
            {
              item.form.map((item2, j) => {
                return (
                    <Form keyNo={j} dataType="sub"  module={t.state.module} status={t.state.status} form={item2}  data={t.state.itemParam.value[i]} fieldControll={t.state.fieldControll}  onChange={this.changeSub.bind(this,this.state.itemParam,i)}/>
                  )}
              )
            }
          </div>
          </div>
        )
      });
  }

   //预览附件
	viewFile(file) {
    var id = file.id;
    var fileExt = file.fileExt;
		downloadFile(id,'android',fileExt);
  }
  
  clickPop(){
    if(!this.state.itemParam.readOnly){
      Toast.show({
        content:"移动端暂不支持该类型编辑"
      });
      return false;
    }
  }

  clickText(){
    if(!this.state.itemParam.readOnly){
      var cannotEdit = this.state.itemParam.cannotEdit;
      if(typeof(cannotEdit) == 'undefined' || cannotEdit == null){
        cannotEdit = true;
      }
      if(!cannotEdit){
        Toast.show({
          content:"移动端暂不支持该类型编辑"
        });
        return false;
      }
    }
  }


  //说明点击
  noticeClick(url){
    if(url != ''){
      pageSkipDirectly(url);
    }
  }


  //检查是否有html标签
  checkHtml(htmlStr) {
    var  reg = /<[^>]+>/g;
    return reg.test(htmlStr);
  }


  render() {
    const t = this;
    const radioFieldProps = {
      groupListArgument: {
        lineIndent: 15,
        itemIndent: 15,
      },
      groupListFlag: true,
      className:"dd-ques-title",
      iconPosition: 'left',
    };

    const CheckboxFieldProps = {
      groupListArgument: {
        lineIndent: 15,
        itemIndent: 15,
      },
      groupListFlag: true,
      className:"dd-ques-title",
      mode:"slot"
    };
    let maxDate = new Date();
    maxDate.setFullYear(maxDate.getFullYear() + 1);
    let minDate = new Date();
    minDate.setDate(minDate.getDate()-1);
    
    return (
      <div className={this.state.itemParam.isHidden?"t-DN":""}>
        { this.state.itemParam.itemType == 'text' ?
          <Group.List borderTopNone={true}>
            <div onClick={t.clickText.bind(t,t.state.itemParam)}>
              <TextField
              required={t.state.itemParam.required}
              readOnly={t.state.itemParam.readOnly || t.state.itemParam.cannotEdit==false}
              label={t.state.itemParam.title}
              placeholder={t.state.itemParam.readOnly || t.state.itemParam.cannotEdit==false?'':t.state.itemParam.placeholder}
              value={t.state.itemParam.value}
              onChange={(value) => { t.handleTextChange(t.state.itemParam, value); }}
            >
            </TextField>
            </div>
          </Group.List>
          :this.state.itemParam.itemType == 'html' ?
          <Group.List borderTopNone={true}>
             {t.checkHtml(t.state.itemParam.value)?
             <div className=""  onClick={this.clickPop.bind(this)}>
             <div className={this.state.label==''?'t-DN':'t-field-box t-FBH t-FBAC t-FBJ'}>
               <div className={this.state.required?'t-field-layout-h-label t-FS16 required':'t-field-layout-h-label t-FS16'}>{t.state.itemParam.title}</div>
             </div>
             <div className="formContent" >
              <div  dangerouslySetInnerHTML={{__html: t.state.itemParam.value}}></div>
              </div>
             </div>
             :<TextareaField
                required={t.state.itemParam.required}
                label={t.state.itemParam.title}
                readOnly={t.state.itemParam.readOnly}
                minRows={3}
                layout="v"
                placeholder={t.state.itemParam.readOnly?'':t.state.itemParam.placeholder}
                value={t.state.itemParam.value}
                onChange={(value) => { t.handleTextAreaChange(t.state.itemParam, value); }}
              />
             }
          </Group.List>
          : this.state.itemParam.itemType == 'textarea' ?
            <Group.List borderTopNone={true}>
               <TextareaField
                required={t.state.itemParam.required}
                label={t.state.itemParam.title}
                readOnly={t.state.itemParam.readOnly}
                minRows={3}
                placeholder={t.state.itemParam.readOnly?'':t.state.itemParam.placeholder}
                value={t.state.itemParam.value}
                onChange={(value) => { t.handleTextAreaChange(t.state.itemParam, value); }}
              />
            </Group.List>
            : this.state.itemParam.itemType == 'radio' ?
              <Group.List borderTopNone={true}>
                <SelectField
                    required={t.state.itemParam.required}
                    label={t.state.itemParam.title}
                    readOnly={t.state.itemParam.readOnly}
                    options={t.state.itemParam.selectOptions}
                    placeholder={t.state.itemParam.readOnly?'':t.state.itemParam.placeholder}
                    onSelect={t.selectChange.bind(t,t.state.itemParam.key)}
                    value={t.state.itemParam.value}
                  />
               </Group.List>
              : this.state.itemParam.itemType == 'checkbox' ?
                <Group.List borderTopNone={true}>
                  <CheckboxField
                  required={t.state.itemParam.required}
                  readOnly={t.state.itemParam.readOnly}
                  //  required={t.state.itemParam.required} 
                   placeholder={t.state.itemParam.readOnly?'':t.state.itemParam.placeholder}
                   data={t.state.itemParam.selectOptions} {...CheckboxFieldProps} 
                   iconPosition="right" 
                   label={t.state.itemParam.title}
                   onChange={t.checkboxChange.bind(t,t.state.itemParam.key)}/>
                   </Group.List>
                : this.state.itemParam.itemType == 'select' ?
                  <Group.List borderTopNone={true}>
                  <SelectField
                    required={t.state.itemParam.required}
                    label={t.state.itemParam.title}
                    readOnly={t.state.itemParam.readOnly}
                    options={t.state.itemParam.selectOptions}
                    placeholder={t.state.itemParam.readOnly?'':t.state.itemParam.placeholder}
                    onSelect={t.selectChange.bind(t,t.state.itemParam.key)}
                    value={t.state.itemParam.value}
                  />
                   </Group.List>
                  : this.state.itemParam.itemType == 'datetime' ?
                    <Group.List borderTopNone={true}>
                      <DatetimeField label={t.state.itemParam.title}
                      required={t.state.itemParam.required}
                      readOnly={t.state.itemParam.readOnly}
                      onSelect={t.handleChangeDate.bind(t, t.state.itemParam.key)} 
                      value={t.state.itemParam.value}
                      columns={DatetimeField[t.state.itemParam.dateFormat]}
                      placeholder={t.state.itemParam.readOnly?'':t.state.itemParam.placeholder} />
                    </Group.List>
                    : this.state.itemParam.itemType == 'datetimeStep' ?
                    <Group.List borderTopNone={true}>
                      <HBox className="t-field-box t-FBAC">
                        <div className={t.state.itemParam.required?"t-field-layout-h-label t-FS16 required":"t-field-layout-h-label t-FS16"}>{t.state.itemParam.title}</div>
                        <HBox flex="1" onClick={()=>{t.showSlot(t.state.itemParam.key)}} className="t-FBAC">
                          <Box flex="1"><span className="t-FL t-FS16">{t.state.itemParam.selectValue}</span></Box>
                          {t.state.itemParam.readOnly? "":
                            <Box className="t-FBAC t-field-icon">
                              <AngleRight width={20} fill="#ccc"/>
                              <Datetime
                                locale="zh-cn"
                                minuteStep={5}
                                slotRef={(s) => t[t.state.itemParam.key] = s}
                                title="日期选择"
                                value={t.state.itemParam.value}
                                columns={t.state.itemParam.dateFormat == 'YMDHM' ? Datetime.YMDHM : Datetime.YMD}
                                onConfirm={t.handleChangeDateStep.bind(t, t.state.itemParam.key)}
                                minDate={t.state.itemParam.key == 'cycle_end_time' ? minDate.getTime() : new Date(1900, 0, 1).getTime()}
                                maxDate={t.state.itemParam.key == 'cycle_end_time' ? maxDate.getTime() : (new Date(2051, 0, 1).getTime() - 1)}
                              />
                            </Box>
                          }
                        </HBox>
                      </HBox>
                    </Group.List>
                    : this.state.itemParam.itemType == 'poppage' ?
                      <Group.List borderTopNone={true}>
                       <Poppage 
                          required={t.state.itemParam.required}
                          label={t.state.itemParam.title}
                          readOnly={t.state.itemParam.readOnly}
                          placeholder={t.state.itemParam.readOnly?'':t.state.itemParam.placeholder}
                          popCode={t.state.itemParam.popCode}
                          checked={t.state.itemParam.chooseWay}
                          onChange={this.popageChange.bind(this,t.state.itemParam.key)}
                          value={this.state.itemParam.value}
                        />
                      </Group.List>
                    : this.state.itemParam.itemType == 'popuser' ?
                    <Group.List borderTopNone={true}>
                      <SelectMember 
                        required={t.state.itemParam.required}
                        readOnly={t.state.itemParam.readOnly}
                        label={t.state.itemParam.title}
                        placeholder={t.state.itemParam.placeholder?t.state.itemParam.placeholder:'请选择'}
                        code={t.state.itemParam.code}
                        chooseType={t.state.itemParam.chooseType}
                        checkType={t.state.itemParam.checkType}
                        fieldDataValue={t.state.itemParam.value} 
                        scopeTable={t.state.itemParam.scopeTable}
                        fieldTable={t.state.itemParam.fieldTable} 
                        fieldData={t.state.itemParam.fieldData} 
                        ref={"selectMember_"+t.state.itemParam.fieldData}
                        isDelete={!t.state.itemParam.readOnly}
                        showType="list" 
                        onChange={this.popuserChange.bind(this,t.state.itemParam.key)}
                        includeDel={t.state.itemParam.readOnly ? "1" : "0"}
                      />
                    </Group.List>
                    : this.state.itemParam.itemType == 'upload' ?
                      <Group.List borderTopNone={true} className="t-PB16">
                        <Upload
                          ref={"upload"+t.state.itemParam.tableName+"_"+t.state.itemParam.key}
                          required={t.state.itemParam.required}
                          canAdd={t.state.itemParam.readOnly==true?false:true}
                          canDel={t.state.itemParam.readOnly==true?false:true}
                          label={t.state.itemParam.title}
                          initList={t.state.itemParam.value}
                          initIds={t.state.itemParam.initIds}
                          dir={t.state.module}
                          limitNo={t.state.itemParam.uploadFileNumLimit}
                          extensions={t.state.itemParam.uploadFileLimit}
                          fileSizeLimit={0}
                          onChange={(value,isInit) => { t.handleChangePic(t.state.itemParam.key, value,isInit); }}
                          onDel={(value) => { t.handleChangePic(t.state.itemParam.key, value); }}/>
                      </Group.List>
                    : this.state.itemParam.itemType == 'image' ?
                      <Group.List borderTopNone={true}>
                        <Upload
                          ref={"upload"+t.state.itemParam.tableName+"_"+t.state.itemParam.key}
                          required={t.state.itemParam.required}
                          canAdd={t.state.itemParam.readOnly==true?false:true}
                          canDel={t.state.itemParam.readOnly==true?false:true}
                          label={t.state.itemParam.title}
                          initList={t.state.itemParam.value}
                          initIds={t.state.itemParam.initIds}
                          dir={t.state.module}
                          uploadType="image"
                          limitNo={t.state.itemParam.uploadFileNumLimit}
                          extensions={t.state.itemParam.uploadFileLimit}
                          fileSizeLimit={0}
                          onChange={(value,isInit) => { t.handleChangePic(t.state.itemParam.key, value,isInit); }}
                          onDel={(value) => { t.handleChangePic(t.state.itemParam.key, value); }}/>
                      </Group.List>
                    : this.state.itemParam.itemType == 'comment' ?
                      <Group.List borderTopNone={true}>
                        <div className="t-field-layout-v-label t-FS16">{t.state.itemParam.title}</div>
                        <CommentList list={t.state.itemParam.value}/> 
                      </Group.List>
                    : this.state.itemParam.itemType == 'note' && (( this.props.status!="0" && this.state.itemParam.explainShow == false)|| this.props.status=="0") ?
                    <Group.List borderTopNone={true}>
                      <HBox vAlign="center" className="t-LH40  t-FCddblue t-BCf dd-bottom-border t-PL16 t-PR16" onClick={this.noticeClick.bind(this,t.state.itemParam.explainUrl)}>
                        <Box flex={1} className="t-PR">
                          <svg className="dd-svg" width="18" height="18" viewBox="0 0 24 24" aria-labelledby="title">
                            <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
                          </svg>
                          <span className="t-ML26">{t.state.itemParam.explain}</span>
                        </Box>
                        <Box className={t.state.itemParam.explainUrl == ""?"t-DN":""}>
                        <b className="iconfont icon-back t-rotate-180 t-FCc t-FS16 t-FS14"></b>
                        </Box>
                      </HBox>
                    </Group.List> 
                     : this.state.itemParam.itemType == 'switch' ?
                     <Group.List borderTopNone={true}>
                        <SwitchField
                          required={t.state.itemParam.required}
                          readOnly={t.state.itemParam.readOnly}
                          label={t.state.itemParam.title}
                          on={this.state.itemParam.value}
                          onChange={this.handleWitchChange.bind(t, t.state.itemParam.key)}
                        />
                     </Group.List> 
                     : this.state.itemParam.itemType == 'positioning' ?
                     <Group.List borderTopNone={true}>
                        <div >
                         <Positioning
                          required={t.state.itemParam.required}
                          readOnly={t.state.itemParam.readOnly}
                          label={t.state.itemParam.title}
                          canShowLocate = {t.state.itemParam.canShowLocate== null?'':t.state.itemParam.canShowLocate}
                          placeholder={t.state.itemParam.placeholder?'':t.state.itemParam.placeholder}
                          value={t.state.itemParam.value}
                          onChange={this.handlePositionChange.bind(t, t.state.itemParam.key)}
                        />
                        </div>
                      </Group.List> 
                    : <div></div>
        }
      </div>

    )
  }
}

